package org.monster.dao;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.io.RandomAccessFile;
import java.util.NoSuchElementException;
import java.util.Scanner;

import org.monster.vo.PointVO;

public class PointFileDAO implements PointDAO {

	private String fileName = "C:\\zzz\\point.txt";

	public PointFileDAO() throws Exception {

	}

	@Override
	public void create(PointVO vo) throws Exception {

		OutputStream out = null;

		try {
			out = new FileOutputStream(fileName, true);

			out.write(vo.toString().getBytes());
			out.write("\n".getBytes());
			out.flush();
			out.close();
			out = null;

		} catch (Exception e) {
			throw new Exception("AAAAAAAA");

		} finally {
			if (out != null) {
				try {
					out.close();
				} catch (Exception e) {
				}
			}
		}

	}

	@Override
	public PointVO read(String name) throws Exception {

		Scanner scanner = null;

		try {
			scanner = new Scanner(new File(fileName));

			while (true) {
				String line = scanner.nextLine();
				System.out.println(line);

				if (line.indexOf(name) >= 0) {
					return new PointVO(line.split(":"));
				}
			}

		} catch (NoSuchElementException ee) {

		} catch (Exception e) {
			e.printStackTrace();
			throw new Exception("AAAAAAAA");
		} finally {
			if (scanner != null) {
				try {
					scanner.close();
				} catch (Exception e) {
				}
			}
		}
		return null;

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.monster.dao.PointDAO#delete(java.lang.String)
	 */
	@Override
	public void delete(String name) throws Exception {

		RandomAccessFile ra = null;

		try {
			long before = -1;
			ra = new RandomAccessFile(fileName, "rw");

			while (true) {
				String line = ra.readLine();

				System.out.println(line + ":" + ra.getFilePointer());

				if (line == null) {
					break;
				}

				if (line.indexOf(name) >= 0) {
					ra.seek(before);
					byte[] arr = new byte[(line).getBytes().length];
					ra.write(arr);
					ra.write("\n".getBytes());
				}
				before = ra.getFilePointer();
			}

		} catch (Exception e) {
			e.printStackTrace();
			throw new Exception("AAAAAAAA");
		} finally {
			if (ra != null) {
				try {
					ra.close();
				} catch (Exception e) {
				}
			}
		}

	}

	@Override
	public void list() throws Exception {

		RandomAccessFile ra = null;

		try {

			ra = new RandomAccessFile(fileName, "rw");

			while (true) {
				String line = ra.readLine();
				if (line == null) {
					break;
				}

				System.out.println(line);

			}

		} catch (Exception e) {
			e.printStackTrace();
			throw new Exception("AAAAAAAA");
		} finally {
			if (ra != null) {
				try {
					ra.close();
				} catch (Exception e) {
				}
			}
		}

	}

}
